-- | Misc.hs
-- A module for some helper functions.

module Misc where

import Graphics.Vty

import Data.List
import Data.Char
import System.Locale
import Data.Time.LocalTime
import Data.Time.Format

-- | Print current time.
nowTime = getZonedTime >>= format

-- | Convert UTC string (from jabber:x:delay) to zoned.
utcToZoned :: String -> IO String
utcToZoned t = (utcToLocalZonedTime $
                readTime defaultTimeLocale "%Y%m%dT%H:%M:%S" t) >>= format

format = return . formatTime defaultTimeLocale "%H:%M:%S"

-- | Instance for parsing color.
instance Read Color where
    readsPrec _ value =
      tryParse lst
      where
        tryParse [] = []
        tryParse ((attempt, result):xs) =
          if attempt `isPrefixOf` value
            then [(result, drop (length attempt) value)]
            else tryParse xs

        lst = [ ("black",   black)
              , ("red",     red)
              , ("green",   green)
              , ("yellow",  yellow)
              , ("blue",    blue)
              , ("magenta", magenta)
              , ("cyan",    cyan)
              , ("white",   white)
              , ("def",     black)
              ]

-- | Safely read.
readMaybe :: (Read a) => String -> Maybe a
readMaybe str = if (not $ null rd) && (null leftStr) then Just val else Nothing
    where rd@(~[(val, leftStr)]) = reads str

-- | Is string a number?
isStringNumber :: String -> Bool
isStringNumber num = all isNumber num
